package org.wu.framework.inner.lazy.orm.spring.config;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Role;
import org.wu.framework.inner.lazy.orm.spring.SpringConnectionHandler;
import org.wu.framework.inner.lazy.orm.spring.SpringDataSourceHandler;
import org.wu.framework.lazy.database.datasource.proxy.LazyProxyDataSource;
import org.wu.framework.lazy.database.datasource.proxy.audit.LazyAuditAdapter;
import org.wu.framework.lazy.database.datasource.proxy.handler.ConnectionHandler;
import org.wu.framework.lazy.database.datasource.proxy.handler.DataSourceHandler;
import org.wu.framework.lazy.database.datasource.proxy.handler.JdbcHandlerAdapter;
import org.wu.framework.lazy.database.datasource.proxy.util.LazyDataSourceProxyUtils;

import javax.sql.DataSource;
import java.util.List;

/**
 * description 懒人数据源配置信息
 *
 * @author 吴佳伟
 * @date 2023/05/22 20:39
 */
@ConditionalOnProperty(prefix = "spring.datasource", value = "url")
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class LazyDataSourceProxyAutoConfiguration {


    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @Bean
    public JdbcHandlerAdapter jdbcHandlerAdapter(List<DataSourceHandler> dataSourceHandlerList, List<ConnectionHandler> connectionHandlerList, LazyAuditAdapter lazyAuditAdapter) {
        return new JdbcHandlerAdapter(dataSourceHandlerList, connectionHandlerList, lazyAuditAdapter);
    }


    // TODO  兼容其他框架使用的数据源代理
    @Bean
    @Primary
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @ConditionalOnProperty(prefix = "spring.datasource",value = "use-proxy", havingValue = "true",matchIfMissing = true)
    public LazyProxyDataSource lazyProxyDataSource(DataSource dataSource,
                                            JdbcHandlerAdapter jdbcHandlerAdapter) {
        return LazyDataSourceProxyUtils.proxy(dataSource, jdbcHandlerAdapter);
    }

    /**
     * spring 进行事物管理
     *
     * @return SpringConnectionHandler
     */
    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public SpringConnectionHandler springConnectionHandler() {
        return new SpringConnectionHandler();
    }

    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public SpringDataSourceHandler springDataSourceHandler() {
        return new SpringDataSourceHandler();
    }
}
